<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 租赁房产管理编辑 -->

    <a-spin :spinning="loading">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        :rules="editModel != 0 ? rules : {}"
      >
        <!-- 表单 -->
        <a-card :bordered="false">
          <title-name title="基本信息" />

          <custom-form :form-list="formList" :form="form" :edit-model="editModel == 0 ? '' : ''" />
          <!-- </a-form-model> -->

          <a-row :gutter="24">
            <a-col v-if="editModel !== 0" :md="24" :sm="24">
              <a-form-model-item label="*食品卫生许可证" prop="fileFoodInfos">
                <l-table count="5" :business-code="'OF11'" :upload-arrys.sync="form.fileFoodInfos" />
              </a-form-model-item>
            </a-col>
            <a-col v-else :md="24" :sm="24">
              <a-form-model-item label="*食品卫生许可证" prop="fileFoodInfos">
                <file-link :file-list="form.fileFoodInfos" />
              </a-form-model-item>
            </a-col>
            <!-- 营业执照隐藏
            <a-col v-if="editModel !== 0" :md="24" :sm="24">
              <a-form-model-item label="*营业执照" prop="fileBusinessInfos">
                <l-table count="5" :business-code="'OF11'" :upload-arrys.sync="form.fileBusinessInfos" />
              </a-form-model-item>
            </a-col>
            <a-col v-else :md="24" :sm="24">
              <a-form-model-item label="*营业执照" prop="fileBusinessInfos">
                <file-link :file-list="form.fileBusinessInfos" />
              </a-form-model-item>
            </a-col>
            -->
          </a-row>
        </a-card>
        <a-card :bordered="false">
          <!-- 食堂包间信息 -->
          <title-name title="食堂包间信息" />
          <a-row :gutter="24">
            <a-col :md="24" :sm="24">
              <div class="flex-row mb20">
                <a-button :disabled="editModel == 0" class="ml20" type="primary" @click="addLine()"> 添加行 </a-button>
              </div>
              <s-table
                ref="table"
                bordered
                size="default"
                row-key="key"
                :columns="columns"
                :data="loadData"
                :is-delete="true"
                :alert="true"
                show-size-changer
                show-quick-jumper
                :show-pagination="false"
              >
                <template slot="roomsNum" slot-scope="text, record">
                  <BaseInput
                    v-model="record.roomsNum"
                    :disabled="!record.editable"
                    :value="text"
                    placeholder="请输入"
                  />
                </template>
                <template slot="capacity" slot-scope="text, record">
                  <BaseInputNumber v-model="record.capacity" :disabled="!record.editable" placeholder="请输入" />
                </template>
                <template slot="roomsFile" slot-scope="text, record">
                  <upload-list
                    :disabled="!record.editable"
                    upload-type="image"
                    :business-code="'OF11'"
                    :edit-model="editModel"
                    count="1"
                    :del-request="false"
                    :upload-arrys.sync="record.roomsFile"
                    multiple
                  />
                </template>
                <template slot="action" slot-scope="text, record, index">
                  <span v-if="record.editable">
                    <a @click="() => save(record)">保存</a>
                    <a-divider type="vertical" />
                    <a-popconfirm title="确定要取消保存?" @confirm="() => cancel(record.key, index)">
                      <a>取消</a>
                    </a-popconfirm>
                  </span>
                  <span v-else>
                    <a :disabled="editingKey !== '' || editModel == 0" @click="() => edit(record.key)">编辑</a>
                    <a-divider type="vertical" />
                    <a-popconfirm title="确定要删除?" @confirm="() => del(record, index)">
                      <a :disabled="editingKey !== '' || editModel == 0">删除</a>
                    </a-popconfirm>
                  </span>
                </template>
              </s-table>
            </a-col>
          </a-row>
        </a-card>

        <a-card :bordered="false">
          <!-- 食堂工作人员信息 -->
          <title-name title="食堂工作人员信息" />
          <a-row :gutter="24">
            <a-col :md="24" :sm="24">
              <div class="flex-row mb20">
                <a-button :disabled="editModel == 0" class="ml20" type="primary" @click="addLinePeople()">
                  添加行
                </a-button>
              </div>
              <s-table
                ref="tablePeople"
                bordered
                size="default"
                row-key="key"
                :columns="columnsPeople"
                :data="loadDataPeople"
                :is-delete="true"
                :alert="true"
                show-size-changer
                show-quick-jumper
                :show-pagination="false"
              >
                <template slot="userName" slot-scope="text, record">
                  <!-- <SelectOrgPeople
                        v-if="orgCode"
                        v-model="record.userId"
                        :disabled="!record.editable"
                        :org-ids="[form.orgId]"
                        :request-params="{ orgCodes: [orgCode + 'A'], and: true }"
                        style="max-width: 380px"
                        init
                        placeholder="请选择"
                        :is-array="true"
                        @onSelectChange="onSelectChange($event, record)"
                      />-->
                  <BaseInput v-model="record.userName" :disabled="!record.editable" placeholder="请输入" />

                </template>
                <template slot="postName" slot-scope="text, record">
                  <BaseInput v-model="record.postName" :disabled="!record.editable" placeholder="请输入" />
                </template>
                <template slot="sex" slot-scope="text, record">
                  <a-select v-model="record.sex" :disabled="!record.editable" placeholder="请选择性别">
                    <a-select-option value="男"> 男 </a-select-option>
                    <a-select-option value="女"> 女 </a-select-option>
                  </a-select>
                </template>
                <template slot="age" slot-scope="text, record">
                  <BaseInputNumber v-model="record.age" :disabled="!record.editable" placeholder="请输入" />
                </template>
                <template slot="idCard" slot-scope="text, record">
                  <BaseInput v-model="record.idCard" :disabled="!record.editable" placeholder="请输入" />
                </template>
                <template slot="phone" slot-scope="text, record">
                  <BaseInput v-model="record.phone" :disabled="!record.editable" placeholder="请输入" />
                </template>
                <template slot="address" slot-scope="text, record">
                  <BaseInput v-model="record.address" :disabled="!record.editable" placeholder="请输入" />
                </template>
                <template slot="healthFile" slot-scope="text, record">
                  <upload-list
                    :disabled="!record.editable"
                    :business-code="'OF11'"
                    upload-type="image"
                    :edit-model="editModel"
                    count="1"
                    :del-request="false"
                    :upload-arrys.sync="record.healthFile"
                    multiple
                  />
                </template>
                <template slot="action" slot-scope="text, record, index">
                  <span v-if="record.editable">
                    <a @click="() => savePeople(record)">保存</a>
                    <a-divider type="vertical" />
                    <a-popconfirm title="确定要取消保存?" @confirm="() => cancelPeople(record.key, index)">
                      <a>取消</a>
                    </a-popconfirm>
                  </span>
                  <span v-else>
                    <a :disabled="editingKeyPeople !== '' || editModel == 0" @click="() => editPeople(record.key)"
                      >编辑</a
                    >
                    <a-divider type="vertical" />
                    <a-popconfirm title="确定要删除?" @confirm="() => delPeople(record, index)">
                      <a :disabled="editingKeyPeople !== '' || editModel == 0">删除</a>
                    </a-popconfirm>
                  </span>
                </template>
              </s-table>
            </a-col>
          </a-row>
        </a-card>

        <a-card :bordered="false">
          <!-- 食堂食材采购供应商管理 -->
          <title-name title="食堂食材采购供应商管理" />
          <a-row :gutter="24">
            <a-col :md="24" :sm="24">
              <div class="flex-row mb20">
                <a-button :disabled="editModel == 0" class="ml20" type="primary" @click="addLineSupplier()">
                  添加行
                </a-button>
              </div>
              <s-table
                ref="tableSupplier"
                bordered
                size="default"
                row-key="key"
                :columns="columnsSupplier"
                :data="loadDataSupplier"
                :is-delete="true"
                :alert="true"
                show-size-changer
                show-quick-jumper
                :show-pagination="false"
              >
                <template slot="supplierName" slot-scope="text, record">
                  <BaseInput
                    v-model="record.supplierName"
                    :disabled="!record.editable"
                    :value="text"
                    placeholder="请输入"
                  />
                </template>
                <template slot="foodTypes" slot-scope="text, record">
                  <BaseInput v-model="record.foodTypes" :disabled="!record.editable" placeholder="请输入" />
                </template>
                <template slot="contacts" slot-scope="text, record">
                  <BaseInput v-model="record.contacts" :disabled="!record.editable" placeholder="请输入" />
                </template>
                <template slot="contactsPhone" slot-scope="text, record">
                  <BaseInput v-model="record.contactsPhone" :disabled="!record.editable" placeholder="请输入" />
                </template>
                <template slot="status" slot-scope="text, record">
                  <span>{{ record.status == 1 ? '可用' : '不可用' }}</span>
                </template>
                <template slot="licenseFile" slot-scope="text, record">
                  <upload-list
                    :disabled="!record.editable"
                    :business-code="'OF11'"
                    upload-type="image"
                    :edit-model="editModel"
                    count="1"
                    :del-request="false"
                    :upload-arrys.sync="record.licenseFile"
                    multiple
                  />
                </template>
                <template slot="action" slot-scope="text, record, index">
                  <span v-if="record.editable">
                    <a-popconfirm title="确定保存，保存后不可编辑/删除" @confirm="() => saveSupplier(record)">
                      <a>保存</a>
                    </a-popconfirm>

                    <a-divider type="vertical" />
                    <a-popconfirm title="确定要取消保存?" @confirm="() => cancelSupplier(record.key, index)">
                      <a>取消</a>
                    </a-popconfirm>
                  </span>
                  <span v-else>
                    <a-popconfirm v-if="record.status == 1" title="确定要禁用?" @confirm="() => (record.status = 0)">
                      <a :disabled="editModel == 0">禁用</a>
                    </a-popconfirm>
                    <a-popconfirm v-if="record.status == 0" title="确定要启用?" @confirm="() => (record.status = 1)">
                      <a :disabled="editModel == 0">启用</a>
                    </a-popconfirm>
                  </span>
                  <!-- <span v-else>
                                        <a
                                            :disabled="editingKey !== '' || editModel == 0"
                                            @click="() => edit(record.key)"
                                            >编辑</a
                                        >
                                        <a-divider type="vertical" />
                                        <a-popconfirm title="确定要删除?" @confirm="() => delSupplier(record, index)">
                                            <a :disabled="editingKey !== '' || editModel == 0">删除</a>
                                        </a-popconfirm>
                                    </span> -->
                </template>
              </s-table>
            </a-col>
          </a-row>
        </a-card>
        <!--
         <a-card v-if="editModel == 0" :bordered="false">
            <a-tabs default-active-key="1" @change="callback">
              <a-tab-pane key="1" tab="满意度评价记录">
                <a-alert class="mb12" type="info" show-icon>
                  <template slot="message">
                    <span>
                      平均分：
                      <a>{{ evaluationTotal.avScore }}</a>
                    </span>
                    <a-divider type="vertical" />
                    <span>
                      评价人数：
                      <a>{{ evaluationTotal.num }}</a>
                    </span>
                  </template>
                </a-alert>
                &lt;!&ndash; 表格 &ndash;&gt;
                <s-table
                  ref="evaluation"
                  table-layout="fixed"
                  size="default"
                  row-key="key"
                  :columns="columnsEvaluation"
                  :data="evaluationData"
                  :alert="true"
                  show-size-changer
                  show-quick-jumper
                  show-pagination="auto"
                >
                  <template slot="action" slot-scope="text, record">
                    <a @click="handleEvaluation(record)">查看</a>
                  </template>
                </s-table>
              </a-tab-pane>
              <a-tab-pane key="2" tab="日常考核记录" force-render>
                <a-alert class="mb12" type="info" show-icon>
                  <template slot="message">
                    <span>
                      平均分：
                      <a>{{ AssessmentTotal.avScore }}</a>
                    </span>
                    <a-divider type="vertical" />
                    <span>
                      考核次数：
                      <a>{{ AssessmentTotal.num }}</a>
                    </span>
                  </template>
                </a-alert>
                &lt;!&ndash; 表格 &ndash;&gt;
                <s-table
                  ref="Assessment"
                  table-layout="fixed"
                  size="default"
                  row-key="key"
                  :columns="columnsAssessment"
                  :data="AssessmentData"
                  :alert="true"
                  show-size-changer
                  show-quick-jumper
                  show-pagination="auto"
                >
                  <template slot="action" slot-scope="text, record">
                    <a @click="handleAssessment(record)">查看</a>
                  </template>
                </s-table>
              </a-tab-pane>
            </a-tabs>
          </a-card>-->
      </a-form-model>
    </a-spin>
    <!-- 页脚操作栏 -->
    <div class="tool-btns mb20 page-btn-right-top">
      <a-button v-if="editModel != 0" :loading="loading" type="primary" class="button_right" @click="handleSubmit">
        提交
      </a-button>
      <a-button class="ml20" type="primary" @click="handleClose"> 关闭 </a-button>
    </div>
  </base-breadcrumb>
</template>

<script>
import {
  getCanteen,
  addCanteen,
  updateCanteen,
  getPageOfficeCanteenAppraise,
  getPageOfficeCanteenAssessment,
  queryOfficeCanteenAppraiseListTotal,
  queryOfficeCanteenAssessmentListTotal
} from '@/api/office/canteen' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import UploadList from '@/components/UploadList'
import { STable } from '@/components' // 表格
import SelectOrgPeople from '@/components/Select/SelectOrgPeople'
import { getUserDeptByOrgId } from '@/api/union/organizationManagement' // api
import { getOrgIdHierarchy } from '@/api/commons' // api

const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '包间号',
    dataIndex: 'roomsNum',
    scopedSlots: { customRender: 'roomsNum' },
    width: '30%'
  },
  {
    title: '容纳人数',
    dataIndex: 'capacity',
    scopedSlots: { customRender: 'capacity' },
    width: '30%'
  },
  {
    title: '照片',
    dataIndex: 'roomsFile',
    scopedSlots: { customRender: 'roomsFile' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' }
  }
]
const columnsPeople = [
  {
    title: '序号',
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '姓名',
    dataIndex: 'userName',
    scopedSlots: { customRender: 'userName' },
    width: '10%'
  },
  {
    title: '岗位',
    dataIndex: 'postName',
    scopedSlots: { customRender: 'postName' }
  },
  {
    title: '性别',
    dataIndex: 'sex',
    scopedSlots: { customRender: 'sex' },
    width: '6%'
  },
  {
    title: '年龄',
    dataIndex: 'age',
    scopedSlots: { customRender: 'age' }
  },
  {
    title: '身份证号',
    dataIndex: 'idCard',
    scopedSlots: { customRender: 'idCard' }
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    scopedSlots: { customRender: 'phone' }
  },
  {
    title: '住址',
    dataIndex: 'address',
    scopedSlots: { customRender: 'address' }
  },
  {
    title: '健康证',
    dataIndex: 'healthFile',
    scopedSlots: { customRender: 'healthFile' },
    width: '10%'
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' }
  }
]
const columnsSupplier = [
  {
    title: '序号',
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '供应商名称',
    dataIndex: 'supplierName',
    scopedSlots: { customRender: 'supplierName' }
  },
  {
    title: '供应食材种类',
    dataIndex: 'foodTypes',
    scopedSlots: { customRender: 'foodTypes' }
  },
  {
    title: '联系人',
    dataIndex: 'contacts',
    scopedSlots: { customRender: 'contacts' }
  },
  {
    title: '联系电话',
    dataIndex: 'contactsPhone',
    scopedSlots: { customRender: 'contactsPhone' }
  },
  {
    title: '资质',
    dataIndex: 'licenseFile',
    scopedSlots: { customRender: 'licenseFile' }
  },
  {
    title: '状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' }
  }
]
const columnsEvaluation = [
  {
    title: '序号',
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '评价时间',
    dataIndex: 'createTime'
  },
  {
    title: '得分(90分)',
    dataIndex: 'score'
  },
  {
    title: '评价人',
    dataIndex: 'creatorName'
  },
  {
    title: '考核明细',
    dataIndex: 'action',
    width: '10%',
    scopedSlots: { customRender: 'action' }
  }
]
const columnsAssessment = [
  {
    title: '序号',
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '考核时间',
    dataIndex: 'createTime'
  },
  {
    title: '得分(100分)',
    dataIndex: 'totalScore'
  },
  {
    title: '考核人',
    dataIndex: 'creatorName'
  },
  {
    title: '考核明细',
    dataIndex: 'action',
    width: '10%',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  components: {
    UploadList,
    STable,
    SelectOrgPeople
  },
  extends: new BaseEditPage(),
  data() {
    this.columns = columns
    this.columnsPeople = columnsPeople
    this.columnsSupplier = columnsSupplier
    this.columnsEvaluation = columnsEvaluation
    this.columnsAssessment = columnsAssessment
    return {
      loading: false, // 加载控件
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      form: {
        orgIdStr: '',
        orgId: '',
        status: 1,
        roomsList: [],
        staffList: [],
        supplierList: []
      }, // 表单
      rules: {
        canteenName: [{ required: true, message: '请输入食堂名称', trigger: 'change' }],
        maintainerName: [{ required: true, message: '请输入经营者名称', trigger: 'change' }],
        scale: [{ required: true, message: '请输入规模', trigger: 'change' }],
        // lessorTel: [{ required: true, validator: lessorTel, trigger: 'change' }],
        maxNumPeople: [{ required: true, message: '请输入最多容纳人数', trigger: 'change' }],
        licenseDate: [{ required: true, message: '请选择食品卫生许可证日期 ', trigger: 'change' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        fileFoodInfos: [{ type: 'array', required: true, message: '请上传文件', trigger: 'blur' }],
        //fileBusinessInfos: [{ type: 'array', required: true, message: '请上传文件', trigger: 'blur' }]
      }, // 校验规则
      getUserDeptByOrgId: getUserDeptByOrgId,
      init: false, // 初始化控件
      key: 0,
      keyPeople: 0,
      keySupplier: 0,
      cacheData: {},
      cacheDataPeople: {},
      cacheDataSupplier: {},
      editingKey: '',
      editingKeyPeople: '',
      editingKeySupplier: '',
      userInfo: {},
      isInit: false,
      orgCode: '',
      loadData: () => {
        return new Promise((resolve, reject) => {
          resolve({
            data: this.form.roomsList
          })
        })
      },
      loadDataPeople: () => {
        return new Promise((resolve, reject) => {
          resolve({
            data: this.form.staffList
          })
        })
      },
      loadDataSupplier: () => {
        return new Promise((resolve, reject) => {
          resolve({
            data: this.form.supplierList
          })
        })
      },
      evaluationTotal: {},
      AssessmentTotal: {},
      evaluationData: (parameter) => {
        if (!this.form.orgId) return
        const requestParameters = Object.assign({}, parameter, { query: { unitId: this.form.orgId } })
        this.queryOfficeCanteenAppraiseListTotal(requestParameters)
        return getPageOfficeCanteenAppraise(requestParameters).then((res) => {
          return res
        })
      },
      AssessmentData: (parameter) => {
        if (!this.form.orgId) return
        const requestParameters = Object.assign({}, parameter, { query: { unitId: this.form.orgId } })
        this.queryOfficeCanteenAssessmentListTotal(requestParameters)
        return getPageOfficeCanteenAssessment(requestParameters).then((res) => {
          return res
        })
      }
    }
  },
  watch: {
    // 监听附件实现附件校验
    'form.fileFoodInfos'() {
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          this.$refs.ruleForm?.validateField('fileFoodInfos')
        })
      }
    },
    'form.fileBusinessInfos'() {
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          this.$refs.ruleForm?.validateField('fileBusinessInfos')
        })
      }
    },
    'form.orgId'() {
      getOrgIdHierarchy({ orgIds: [this.form.orgId] }).then((res) => {
        this.orgCode = res.data?.filter((i) => i.tagCode == 'PD' || i.tagCode == 'BC' || i.tagCode == 'CO')[0].tagCode
        console.log(this.orgCode)
      })
    }
  },
  mounted() {
    this.userInfo = this.$userInfo()
    this.form.orgIdStr =
      (this.userInfo.currentPost.code === 'PD' ? this.userInfo.currentPost.orgName + '-' : '') +
      this.userInfo.currentPost.name

    this.$route.meta.title = ['食堂信息维护查看', '食堂信息维护编辑', '食堂信息维护新增'][this.editModel]
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.loading = true
      getCanteen(this.id)
        .then((res) => {
          this.loading = false
          res.data.licenseDate = []
          res.data.licenseDate[0] = res.data.licenseDateStart
          res.data.licenseDate[1] = res.data.licenseDateEnd

          this.form = { ...res.data }
          if(!this.form.roomsList){
            this.form.roomsList = []
          }
          this.form.staffList?.forEach((i) => {
            i.key = this.keyPeople
            this.keyPeople++
          })
          this.form.roomsList?.forEach((i) => {
            i.key = this.key
            this.key++
          })
          this.form.supplierList?.forEach((i) => {
            i.key = this.keySupplier
            this.keySupplier++
          })

          this.$refs.table.refresh(true)
          this.$refs.tablePeople.refresh(true)
          this.$refs.tableSupplier.refresh(true)
          this.$nextTick(() => {
            this.init = true
          })
          if (this.editModel == 0) {
            this.$refs.evaluation.refresh(true)
          }
        })

        .catch(() => {
          this.loading = false
        })
    } else {
      this.form.orgId = this.userInfo.currentPost.id
      /*start--20240125（guchao）【食堂包间信息】 变为非必填*/
      //this.addLine()
      /*end*/

      this.addLinePeople()
      this.addLineSupplier()
      this.$nextTick(() => {
        this.init = true
      })
    }
  },
  computed: {
    formList() {
      return [
        {
          keyName: 'orgIdStr',
          type: 'BaseInput',
          label: '单位',
          disabled: true
        },
        {
          keyName: 'canteenName',
          type: 'BaseInput',
          disabled: this.editModel === 0,
          label: '食堂名称'
        },
        {
          keyName: 'scale',
          type: 'BaseInputNumber',
          disabled: this.editModel === 0,
          label: '规模(m²)：'
        },
        {
          keyName: 'maxNumPeople',
          type: 'BaseInputNumber',
          disabled: this.editModel === 0,
          label: '最多容纳人数'
        },
        {
          keyName: 'licenseDate',
          type: 'a-range-picker',
          disabled: this.editModel === 0,
          placeholder: ['请选择日期', '请选择日期'],
          label: '食品卫生许可证日期',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'maintainerName',
          type: 'BaseInput',
          disabled: this.editModel === 0,
          label: '经营者名称'
        },
        {
          keyName: 'status',
          type: 'a-select',
          disabled: this.editModel === 0,
          label: '状态',
          data: [
            {
              label: '可用',
              value: 1
            },
            {
              label: '不可用',
              value: 0
            }
          ]
        }
      ]
    }
  },

  methods: {
    handleEvaluation(record) {
      let query = record
      this.$router.push({
        name: '/office/canteen/InformationMaintenance/updateEvaluation',
        query
      })
    },
    handleAssessment(record) {
      let query = record
      this.$router.push({
        name: '/office/canteen/InformationMaintenance/updateAssessment',
        query
      })
    },
    //统计
    queryOfficeCanteenAppraiseListTotal(requestParameters) {
      queryOfficeCanteenAppraiseListTotal(requestParameters).then((res) => {
        this.evaluationTotal = res.data
      })
    },
    //统计
    queryOfficeCanteenAssessmentListTotal(requestParameters) {
      queryOfficeCanteenAssessmentListTotal(requestParameters).then((res) => {
        this.AssessmentTotal = res.data
      })
    },
    //人员选择回调
    onSelectChange(e, record) {
      console.log(record)
      console.log(e)
      record.postName = e.postPNames.toString()
      if (e.sex == 1) {
        record.sex = '男'
      } else if (e.sex == 0) {
        record.sex = '女'
      } else {
        record.sex = e.sex
      }
      record.age = e.age
      record.idCard = e.idCard
      record.phone = e.phoneNum
    },
    addLine() {
      this.form.roomsList.push({
        key: this.key,
        capacity: '',
        roomsFile: [],
        roomsNum: '',
        isSave: false,
        editable: true
      })
      this.key++
      this.cacheData = this.form.roomsList.map((item) => ({ ...item }))
      this.$refs.table.refresh(true)
    },
    cancel(key, index) {
      const newData = [...this.form.roomsList]
      const target = newData.filter((item) => key === item.key)[0]
      this.editingKey = ''
      if (target.isSave) {
        if (target) {
          Object.assign(target, this.cacheData.filter((item) => key === item.key)[0])
          delete target.editable
          this.form.roomsList = newData
        }
      } else {
        this.form.roomsList.splice(index, 1)
      }

      this.$refs.table.refresh(true)
    },
    save(data) {
      if (data.roomsNum == '' || data.capacity == '' || data.roomsFile?.length == 0) {
        this.$message.warning('请填写完成后保存！')
        return
      }
      data.isSave = true
      data.editable = false
      this.editingKey = ''
      this.$refs.table.refresh(true)
    },
    edit(key) {
      console.log(key)
      const newData = [...this.form.roomsList]
      const target = newData.filter((item) => key === item.key)[0]
      this.editingKey = key
      if (target) {
        target.editable = true
        target.isSave = true
        this.form.roomsList = newData
      }
      this.cacheData = this.form.roomsList.map((item) => ({ ...item }))
      this.$refs.table.refresh(true)
    },
    del(data, idx) {
      this.form.roomsList.splice(idx, 1)
      this.$refs.table.refresh(true)
    },

    addLinePeople() {
      this.form.staffList.push({
        key: this.keyPeople,
        userId: '',
        postName: '',
        sex: '',
        age: '',
        idCard: '',
        phone: '',
        address: '',
        healthFile: [],
        isSave: false,
        editable: true
      })
      this.keyPeople++
      this.cacheDataPeople = this.form.staffList.map((item) => ({ ...item }))
      this.$refs.tablePeople.refresh(true)
    },
    cancelPeople(key, index) {
      const newData = [...this.form.staffList]
      const target = newData.filter((item) => key === item.key)[0]
      this.editingKeyPeople = ''
      if (target.isSave) {
        if (target) {
          Object.assign(target, this.cacheDataPeople.filter((item) => key === item.key)[0])
          delete target.editable
          this.form.staffList = newData
        }
      } else {
        this.form.staffList.splice(index, 1)
      }

      this.$refs.tablePeople.refresh(true)
    },
   validateIdCard(idNumber){
      const pattern = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/;
      return pattern.test(idNumber);
   },
    validatePhoneNumber(phoneNumber) {
      const pattern = /^1[3-9]\d{9}$/;
      return pattern.test(phoneNumber);
    },
    savePeople(data) {
      /*start--20240125（guchao）【提交验证】 */
      if (
        // data.userId == '' ||
        data.userName == '' ||
        data.postName == '' ||
        data.sex == '' ||
        data.age == '' ||
        data.idCard == '' ||
        data.phone == '' ||
        data.address == '' ||
        data.healthFile?.length == 0
      ) {
        this.$message.warning('请填写完成后保存！')
        return
      }
      if (!this.validateIdCard(data.idCard)) {
        this.$message.warning('不是有效的身份证！')
        return
      }
      if (!this.validatePhoneNumber(data.phone)) {
        this.$message.warning('不是有效的手机号！')
        return
      }
      /*end*/

      if (data) data.isSave = true
      data.editable = false
      this.editingKeyPeople = ''
      this.$refs.tablePeople.refresh(true)
    },
    editPeople(key) {
      console.log(key)
      const newData = [...this.form.staffList]
      const target = newData.filter((item) => key === item.key)[0]
      this.editingKeyPeople = key
      if (target) {
        target.editable = true
        target.isSave = true
        this.form.staffList = newData
      }
      this.cacheDataPeople = this.form.staffList.map((item) => ({ ...item }))
      this.$refs.tablePeople.refresh(true)
    },
    delPeople(data, idx) {
      this.form.staffList.splice(idx, 1)
      this.$refs.tablePeople.refresh(true)
    },

    addLineSupplier() {
      this.form.supplierList.push({
        key: this.keySupplier,
        contacts: '',
        contactsPhone: '',
        foodTypes: '',
        status: '1',
        supplierName: '',
        licenseFile: [],
        isSave: false,
        editable: true
      })
      this.keySupplier++
      this.cacheDataSupplier = this.form.supplierList.map((item) => ({ ...item }))
      this.$refs.tableSupplier.refresh(true)
    },
    cancelSupplier(key, index) {
      const newData = [...this.form.supplierList]
      const target = newData.filter((item) => key === item.key)[0]
      this.editingKeySupplier = ''
      if (target.isSave) {
        if (target) {
          Object.assign(target, this.cacheDataSupplier.filter((item) => key === item.key)[0])
          delete target.editable
          this.form.supplierList = newData
        }
      } else {
        this.form.supplierList.splice(index, 1)
      }

      this.$refs.tableSupplier.refresh(true)
    },
    saveSupplier(data) {
      if (
        data.supplierName == '' ||
        data.foodTypes == '' ||
        data.contacts == '' ||
        data.contactsPhone == '' ||
        data.licenseFile?.length == 0
      ) {
        this.$message.warning('请填写完成后保存！')
        return
      }
      data.isSave = true
      data.editable = false
      this.editingKeySupplier = ''
      this.$refs.tableSupplier.refresh(true)
    },
    editSupplier(key) {
      console.log(key)
      const newData = [...this.form.supplierList]
      const target = newData.filter((item) => key === item.key)[0]
      this.editingKeySupplier = key
      if (target) {
        target.editable = true
        this.form.supplierList = newData
      }
      this.cacheDataSupplier = this.form.supplierList.map((item) => ({ ...item }))
      this.$refs.tableSupplier.refresh(true)
    },
    delSupplier(data, idx) {
      this.form.supplierList.splice(idx, 1)
      this.$refs.tableSupplier.refresh(true)
    },
    callback(key) {
      if (key == 2 && !this.isInit) {
        this.isInit = true //第一次切换加载
        this.$refs.Assessment.refresh(true)
      }
    },
    validateTable() {
      let flag = false
      this.form.roomsList.forEach((i) => {
        if (i.editable) {
          flag = i.editable
        }
      })
      this.form.staffList.forEach((i) => {
        if (i.editable) {
          flag = i.editable
        }
      })
      this.form.supplierList.forEach((i) => {
        if (i.editable) {
          flag = i.editable
        }
      })
      return flag
    },
    /**
     * 提交表单
     */
    handleSubmit() {
      let that = this
      let api = [updateCanteen, addCanteen][that.editModel - 1] // 根据操作切换url地址
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        if (e) {
          // 提交表单
          if (
            this.form.supplierList.length == 0 ||
            this.form.staffList.length == 0
            //this.form.roomsList.length == 0
          ) {
            this.$message.warning('供应商和员工信息至少需要一条数据')
            return
          }
          if (this.validateTable()) {
            this.$message.warning('请保存表格数据后提交！')
            return
          }
          that.loading = true
          that.form.licenseDateStart = that.form.licenseDate[0]
          that.form.licenseDateEnd = that.form.licenseDate[1]
          let form = that.$clone(that.form)
          api(form)
            .then(() => {
              that.loading = false
              that.$message.success('提交成功！')
              that.$multiTab.close()
            })
            .catch(() => {
              that.loading = false
            })
        }
      })
    },
    handleClose() {
      if (this.isAudit) {
        window.close()
      } else {
        this.$multiTab.close(this.$route.fullpath)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.file_prompt {
  color: #999;
}
</style>